export type ThemeNames = "dark" | "light"

export type ThemeFunc = (theme: ThemeNames) => void

let funcs: ThemeFunc[] = []

// 监听系统主题切换
let media = window.matchMedia('(prefers-color-scheme:dark)');
//监听样式切换
let callback = e => {
  let prefersDarkMode = e.matches;
  if (prefersDarkMode) {
    funcs.forEach(i => {
      i("dark")
    })
  } else {
    funcs.forEach(i => {
      i("light")
    })
  }
}
if (typeof media.addEventListener === 'function') {
  media.addEventListener('change', callback);
} else if (typeof media.addListener === 'function') {
  media.addListener(callback);
}

export function addEventListener(fun: ThemeFunc, immediate: boolean = false) {
  funcs.push(fun)
  if (immediate) {
    if (media.matches) {
      fun("dark")
    } else {
      fun("light")
    }
  }
}

export function removeEventListener(fun: ThemeFunc) {
  let findIndex = funcs.findIndex(i => i === fun);
  funcs.splice(findIndex, 1)
}

